package com.webssh.service.handler.process;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.webssh.service.handler.HandlerProcess;

public class SHProcessHandler implements HandlerProcess{

	private static final Logger logger = LoggerFactory.getLogger(SHProcessHandler.class);
	
	Process p;
	InputStream in;
	InputStream er;
	PrintWriter out;
	WebSocketSession ws;
	
	public SHProcessHandler(WebSocketSession ws){
		this.ws = ws;
	}
	
	private void init(final InputStream reader, final WebSocketSession ws){
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					byte[] buffer = new byte[1024 * 4];
					StringBuilder builder = new StringBuilder();
					while (ws != null && ws.isOpen()) {
						builder.setLength(0);
                        int size = in.read(buffer);
                        if (size == -1) {
                            return;
                        }
                        for (int i = 0; i < size; i++) {
                            char chr = (char) (buffer[i] & 0xff);
                            builder.append(chr);
                        }
                        ws.sendMessage(new TextMessage(builder.toString()));
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	public void close(){
		if(p != null){
			logger.info("关闭进程:{}", p.toString());
			p.destroy();
			p = null;
		}
		if(in != null){
			try {
				logger.info("关闭InputStream:{}", in.toString());
				in.close();
				in = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(er != null){
			try {
				logger.info("关闭ErrorStream:{}", er.toString());
				er.close();
				er = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(out != null){
			logger.info("关闭OutputStream:{}", out.toString());
			out.close();
			out = null;
		}
	}

	public void handleMessage(String string) throws IOException {
		if(out != null){
			out.println(string);
		}
	}

	@Override
	public void init() throws IOException {
		try {
			this.p = Runtime.getRuntime().exec("/bin/bash");
			this.in = p.getInputStream();
			this.er = p.getErrorStream();
			this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(p.getOutputStream())), true);
			init(er, ws);
			init(in, ws);
		} catch (IOException e) {
			e.printStackTrace();
			close();
		}
		
	}
}
